package com.hspedu.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hspedu.seckill.exception.GlobalException;
import com.hspedu.seckill.mapper.UserMapper;
import com.hspedu.seckill.pojo.User;
import com.hspedu.seckill.service.UserService;
import com.hspedu.seckill.util.CookieUtil;
import com.hspedu.seckill.util.MD5Util;
import com.hspedu.seckill.util.UUIDUtil;
import com.hspedu.seckill.vo.LoginVo;
import com.hspedu.seckill.vo.RespBean;
import com.hspedu.seckill.vo.RespBeanEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;

    //配置RedisTemplate，操作Redis
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        //接收到mobile和password[midPass]
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        //判断手机号和密码是否为空
        // if (!StringUtils.hasText(mobile) || !StringUtils.hasText(password)){
        //     return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        // }

        //校验手机号码是否合格
        // if (!ValidatorUtil.isMobile(mobile)){
        //     return RespBean.error(RespBeanEnum.MOBILE_ERROR);
        // }

        //查询DB，看看用户是否存在
        User user = userMapper.selectById(mobile);
        if (null == user) {//说明用户不存在
            // return RespBean.error(RespBeanEnum.LOGIN_ERROR);
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        //如果用户存在，则比对密码
        //注意从LoginVo取出的密码是中间密码(即客户端经过一次加密加盐处理的密码)
        if (!MD5Util.midPassToDBPass(password, user.getSlat()).equals(user.getPassword())) {
            System.out.println(MD5Util.midPassToDBPass(password, user.getSlat()));
            System.out.println(user.getPassword());
            // return RespBean.error(RespBeanEnum.LOGIN_ERROR);
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        //给每个用户生成唯一的ticket
        String ticket = UUIDUtil.uuid();
        //将登陆成功的用户保存到session中
        //request.getSession().setAttribute(ticket,user);

        //为了实现分布式Session，把登录的用户存放到Redis
        redisTemplate.opsForValue().set("user:" + ticket, user);
        //将ticket保存到cookie
        CookieUtil.setCookie(request, response, "userTicket", ticket);

        //登录成功
        return RespBean.success(ticket);
    }

    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        //如果 cookie 没有生成
        if (!StringUtils.hasText(userTicket)) {
            return null;
        }
        //根据userTicket到Redis获取user
        User user = (User) redisTemplate.opsForValue().get("user:" + userTicket);
        //如果用户不为null，就重新设置cookie，刷新
        if (null != user) {
            CookieUtil.setCookie(request, response, "userTicket", userTicket);
        }

        return user;
    }

    //更新用户密码
    @Override
    public RespBean updatePassword(String userTicket, String password, HttpServletRequest request, HttpServletResponse response) {
        //根据userTicket到Redis获取user
        User user = this.getUserByCookie(userTicket, request, response);
        if (null == user) {
            throw new GlobalException(RespBeanEnum.MOBILE_NOT_EXIST);
        }

        if (!StringUtils.hasText(password)) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        String dbPass = MD5Util.inputPassToDBPass(password, user.getSlat());
        user.setPassword(dbPass);

        int i = userMapper.updateById(user);

        if (i == 1){//更新成功
            //删除redis的缓存对象
            redisTemplate.delete("user:" + userTicket);
            return RespBean.success();
        }

        //更新失败
        return RespBean.error(RespBeanEnum.PASSWORD_UPDATE_ERROR);
    }
}
